package com.yunxiang.service;

import java.util.Date;
import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.yunxiang.plugin.SqlManager;

public class DriverService {
	
	/**
	 * 
	 * @param mobile
	 * @param car_num
	 * @param openId
	 * @return 0:正常返回
	 * 			-1:车牌号和司机不属于同一个物流公司
	 * 			-2:车牌号超过绑定人数限制
	 */
	public Integer bind(String mobile,String car_num,String openId){
		if(!isSameCompany(mobile, car_num))
			return -1;
		if(isOverBindQuantity(car_num))
			return -2;
		
		Record bind = new Record();
		bind.set("OPEND_ID", openId);
		bind.set("MOBILE", mobile);
		bind.set("CAR_NUM", car_num);
		bind.set("CREATE_DATE", new Date());
		
		Db.save("w_bind", bind);
		return 0;
	}

	/**
	 * 根据司机的手机号码判断司机与车牌号是否属于同一家物流公司
	 * @param mobile，司机手机号码
	 * @param car_num，需要绑定的车牌号
	 * @return
	 */
	public boolean isSameCompany(String mobile,String car_num){
		Record company1 = Db.findFirst(SqlManager.sql("driver.isSameCompany1"),mobile);
		Record company2 = Db.findFirst(SqlManager.sql("driver.isSameCompany2"), car_num);
		if(company1 == null)
			return false;
		if(company2 == null)
			return false;
		if(company2.getInt("COMPANY_ID") != company1.getInt("COMPANY_ID"))
			return false;
		return true;
	}
	
	/**
	 * 每个车牌号所能绑定的最大司机数量
	 */
	private final Integer MAX_NUM = 4;
	
	/**
	 * 根据车牌号判断是否超过所能绑定司机的最大数量
	 * @param car_num
	 * @return
	 */
	public boolean isOverBindQuantity(String car_num){
		Record record = Db.findFirst(SqlManager.sql("driver.isOverBindQuantity"), car_num);
		Integer num = Integer.valueOf(record.get("QUANTITY").toString());
		if(num < MAX_NUM)
			return false;
		return true;
	}
	
	/**
	 * 根据openId 判断司机是否绑定了车辆
	 * @param openId
	 * @return
	 */
	public boolean isBind(String openId){
		Record record = Db.findFirst(SqlManager.sql("driver.isBind"), openId);
		return record == null ? false : true;
	}
}
